package controller

import (
	"github.com/gofiber/fiber"
	"github.com/json-iterator/go"
	"gowork/configurationLog/model"
	"strconv"
)

type ConfigurationLogController struct {
	ConfigurationLog *model.ConfigurationLog
}

func (clc *ConfigurationLogController)AddModifyRules(c *fiber.Ctx){

	clc.ConfigurationLog = new(model.ConfigurationLog)

	account := c.FormValue("account")

	ruleStr := c.FormValue("rule")
	var rule model.Rule
	jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(ruleStr), &rule)

	restrictionsStr := c.FormValue("restrictions")
	var restrictions model.ProductPurchaseRestrictions
	jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(restrictionsStr), &restrictions)

	rtStr := c.FormValue("rt")
	rt, err := strconv.Atoi(rtStr)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	cuStr := c.FormValue("cu")
	cu, err := strconv.Atoi(cuStr)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	res , err := clc.ConfigurationLog.AddModifyRules(account, &rule, &restrictions, rt, cu)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	c.JSON(fiber.Map{
		"code": res["code"],
		"data": nil,
		"message": res["message"],
	})
	return
}

func (clc *ConfigurationLogController)ViewLog(c *fiber.Ctx){

	clc.ConfigurationLog = new(model.ConfigurationLog)

	res , err := clc.ConfigurationLog.ViewLog()
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	c.JSON(fiber.Map{
		"code": 200,
		"data": res,
		"message": "成功",
	})
	return
}

func (clc *ConfigurationLogController)ViewLogDetails(c *fiber.Ctx){

	clc.ConfigurationLog = new(model.ConfigurationLog)

	configurationLogIdStr := c.FormValue("configurationLogId")
	configurationLogId, err := strconv.ParseInt(configurationLogIdStr, 10, 64)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	productOrderRestrictionIdStr := c.FormValue("productOrderRestrictionId")
	productOrderRestrictionId, err := strconv.ParseInt(productOrderRestrictionIdStr, 10, 64)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	res , err := clc.ConfigurationLog.ViewLogDetails(configurationLogId, productOrderRestrictionId)
	if err != nil{
		c.JSON(fiber.Map{
			"code": 500,
			"data": nil,
			"message": err.Error(),
		})
		return
	}

	c.JSON(fiber.Map{
		"code": 200,
		"data": res,
		"message": "成功",
	})
	return
}